import React, { useEffect, useState, useMemo } from 'react';
import { Form, Radio, Select, Upload, Button, Input, Row, message } from 'antd';
import { connect } from 'react-redux';
import FormItem from '../../../components/FormItem';
import { APIUrl, APIUrlNoVersion } from '../../../services/createServices';
import { DATA_SOURCE, ENABLE_STATUS } from '../../../utils/constant';
import storage from '../../../utils/storage';
import { headerModules } from '../../../utils/utils';
import services from '../../../services/api';
import DeptSelect from '../../../components/DeptSelect';

const layout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};

const NameListAdd = (props) => {
  const {
    namelist_type = [],
    namelist_data_type = [],
    depts = [],
    actionType,
    form,
    closeModal,
    id,
    history,
    menu,
  } = props;
  const [data, setData] = useState({});
  const [fileList, setFileList] = useState([]);

  useEffect(() => {
    actionType === 'update' && getListDetail();
  }, []);

  const getListDetail = async () => {
    if (props.isAuditLog) {
      setData(props.record)
      return
    }
    const { code, data, msg } = await services.nameList.detail({ name_list_id: id });
    if (!code) {
      setData(data);
    } else {
      message.error(msg);
    }
  };

  const handleUploadChange = ({ fileList, file }) => {
    const { response, status } = file;
    setFileList(fileList);
    if (status === 'done') {
      const { code, data: file_code, msg } = response;
      if (!code) {
        form.setFieldsValue({ file_code });
        setFileList([file]);
      } else {
        form.setFieldsValue({ file_code: '' });
        setFileList([]);
        message.error(msg);
      }
    } else if (status === 'removed') {
      form.setFieldsValue({ file_code: '' });
      setFileList([]);
    } else {
      form.setFieldsValue({ file_code: '' });
    }
  };

  const handleSubmit = () => {
    form.validateFields(async (err, values) => {
      if (!err) {
        const { dept_ids, data_content } = values;
        values.dept_ids = dept_ids.map((item) => item.value);
        // dept_ids.includes(0) && (values.dept_ids = allDeptIds);
        values.data_content = data_content && data_content.split('\n').filter(Boolean);
        const { code, msg } = await services.nameList[actionType]({ ...values, name_list_id: id });
        if (!code) {
          message.success(msg);
          closeModal && closeModal();
          if (props.isAuditLog) return
          history.push('/variable/nameList');
        } else {
          message.error(msg);
        }
      }
    });
  };

  const DeptSelectNode = useMemo(
    () =>
      DeptSelect({
        treeCheckable: true, // 是否多选
        treeCheckStrictly: true, // 多选时是否取消父子关联
        deptTree: depts, // 全部部门数据
        deptArr: {
          ids: data.dept_ids || [],
          name: data.dept_names || [],
        }, // 当前部门数据
        hasRight: true, // 是否需要权限展示
        // nodeDisabled: (item) => !item.dept_id, // 节点禁选
        layout: {
          label: '可见部门',
          ...layout,
        },
        rules: [{ required: true, message: '请选择' }],
        form: form,
      }),
    [data.dept_ids, data.dept_names]
  );

  const getFormItems = () => {
    const {
      list_name,
      list_type,
      data_type,
      // dept_ids = [],
      // dept_names = [],
      remark,
      data_source,
      file_code,
      data_content,
      status,
    } = data;
    return [
      {
        label: {
          label: '名单名称',
          ...layout,
        },
        name: 'list_name',
        options: {
          initialValue: list_name,
          rules: [
            { required: true, message: '请填写' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
          ],
        },
        component: <Input placeholder='请填写' />,
      },
      {
        label: {
          label: '名单类型',
          ...layout,
        },
        name: 'list_type',
        options: {
          initialValue: list_type,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select placeholder='请选择' allowClear style={{ width: '100%' }}>
            {namelist_type.map((item) => (
              <Select.Option value={item.key} key={item.key}>
                {item.value}
              </Select.Option>
            ))}
          </Select>
        ),
      },
      {
        label: {
          label: '数据类型',
          ...layout,
        },
        name: 'data_type',
        options: {
          initialValue: data_type,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select placeholder='请选择' allowClear style={{ width: '100%' }}>
            {namelist_data_type.map((item) => (
              <Select.Option value={item.key} key={item.key}>
                {item.value}
              </Select.Option>
            ))}
          </Select>
        ),
      },
      DeptSelectNode,
      {
        label: {
          label: '描述',
          ...layout,
        },
        name: 'remark',
        options: {
          initialValue: remark,
          rules: [{ max: 256, message: '最长256个字符' }],
        },
        component: <Input.TextArea rows={4} placeholder='请填写' />,
      },
      actionType === 'update' && {
        label: {
          label: '状态',
          ...layout,
        },
        name: 'status',
        options: {
          initialValue: status || ENABLE_STATUS._TRUE,
        },
        component: (
          <Radio.Group>
            <Radio value={ENABLE_STATUS._TRUE}>启用</Radio>
            <Radio value={ENABLE_STATUS._FALSE}>停用</Radio>
          </Radio.Group>
        ),
      },
      {
        label: {
          label: ' 添加数据',
          ...layout,
        },
        name: 'data_source',
        options: {
          initialValue: data_source || DATA_SOURCE._LOCAL,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Radio.Group>
            <Radio value={DATA_SOURCE._LOCAL}>本地上传</Radio>
            <Radio value={DATA_SOURCE._COMSTOM}>手动录入</Radio>
          </Radio.Group>
        ),
      },
      form.getFieldValue('data_source') !== DATA_SOURCE._COMSTOM && {
        label: {
          label: '文件',
          ...layout,
        },
        name: 'file_code',
        options: {
          initialValue: file_code,
          rules: [{ required: actionType !== 'update', message: '请上传文件' }],
        },
        component: (
          <div>
            <Upload
              accept='.xls,.xlsx'
              name='file'
              action={APIUrl + '/namelist/import'}
              showUploadList={{ showRemoveIcon: true, showDownloadIcon: false }}
              fileList={fileList}
              onChange={handleUploadChange}
              headers={{ 'X-User-Dept-Id': storage.dept, modules: headerModules(menu.asideHighlight) }}
            >
              <Button>上传文件</Button>
            </Upload>
            <p>
              支持扩展名 xls、xlsx，点击下载
              <a href={APIUrlNoVersion + '/common/template/namelist.xlsx'}>示例文件</a>
            </p>
          </div>
        ),
      },
      form.getFieldValue('data_source') === DATA_SOURCE._COMSTOM && {
        label: {
          label: '录入数据',
          ...layout,
        },
        name: 'data_content',
        options: {
          initialValue: data_content,
          rules: [{ required: actionType !== 'update', message: '请填写数据内容' }],
        },
        component: (
          <Input.TextArea
            rows={4}
            placeholder='回车换行，每行一条记录，数据与备注用分号分割，&#10;如：192.168.0.1;备注内容&#10;192.168.0.2;备注内容'
          />
        ),
      },
    ].filter(Boolean);
  };

  return (
    <>
      {getFormItems().map((item, index) => (
        <FormItem {...props} key={index} form={form} item={item} colNum={1} modelId={null} />
      ))}
      <Row type='flex' justify='end' align='middle' className='params_button'>
        {actionType !== 'update' && (
          <Button onClick={closeModal} style={{ marginRight: '20px' }}>
            取消
          </Button>
        )}
        <Button type='primary' autoFocus={true} onClick={handleSubmit}>
          确定
        </Button>
      </Row>
    </>
  );
};

function mapStateToProps(state) {
  return {
    menu: state.menu,
  };
}

export default connect(mapStateToProps)(Form.create()(NameListAdd));
